package com.wlz.controller;

import com.wlz.dao.ArticleRepository;
import com.wlz.model.Article;
import com.wlz.resp.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Optional;

/**
 * @author： wlz
 * @Date 2020/12/23 18:43
 * @description： TODO
 * @version: 1.0
 */

@RestController
@RequestMapping("articleRepository")
public class ArticleRepositoryController {

    @Autowired
    private ArticleRepository articleRepository;


    @GetMapping("{id}")
    public JsonResult findById(@PathVariable String id) {
        Optional<Article> article = articleRepository.findById(id);
        JsonResult jsonResult = new JsonResult(true);
        jsonResult.put("article", article.orElse(null));
        return jsonResult;
    }


    @PostMapping("")
    public JsonResult save(@RequestBody Article article) {
        // 新增或更新
        String verifyRes = verifySaveForm(article);
        if (!StringUtils.isEmpty(verifyRes)) {
            return new JsonResult(false, verifyRes);
        }

        if (StringUtils.isEmpty(article.getId())) {
            article.setCreateTime(new Date());
        }

        Article a = articleRepository.save(article);
        boolean res = a.getId() != null;
        return new JsonResult(res, res ? "保存成功" : "");
    }

    @DeleteMapping("{id}")
    public JsonResult delete(@PathVariable String id) {
        // 根据 id 删除
        articleRepository.deleteById(id);
        return new JsonResult(true, "删除成功");
    }


    private String verifySaveForm(Article article) {
        if (article == null || StringUtils.isEmpty(article.getTitle())) {
            return "标题不能为空";
        } else if (StringUtils.isEmpty(article.getContent())) {
            return "内容不能为空";
        }

        return null;
    }
}
